# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify, render_template
import requests
import os
from dotenv import load_dotenv
import prompt
from logger_config import setup_logger

# 加载环境变量
load_dotenv()

# 设置日志记录器
logger = setup_logger()



app = Flask(__name__)

# 获取API密钥和端点
#API_ENDPOINT = "https://api.anthropic.com/v1/messages"
#API_ENDPOINT = "https://api.qingtian.shop/v1/messages"

# 代理设置
# import os
# os.environ['HTTP_PROXY'] = 'http://127.0.0.1:1084'
# os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:1084'

@app.route('/')
def index():
    return render_template('sevenweapon.html')

@app.route('/ppt.html')
def app_page():
    return render_template('ppt.html')  # 需要创建对应的模板文件

def call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint):
    """
    调用AI API的通用函数    
    
    参数:
        user_prompt: 用户输入的提示词
        system_prompt: 系统提示词
    
    返回:
        AI生成的响应
    """
    if not user_prompt:
        logger.error("未提供输入内容")
        return {"error": "未提供输入内容"}, 400
    
    try:
        # 调用大模型API
        response = requests.post(
            api_endpoint,
            headers = {
                "Content-Type": "application/json",
                "anthropic-version": "2023-06-01",
                "x-api-key": api_key,
            },
            json={
                "model": model,
                #"model": "claude-3-7-sonnet-20250219",  # $15.00/1M
                #"model": "claude-3-5-haiku-20241022", # $4.00/1M
                "system": system_prompt,
                "messages": [{"role": "user", "content": user_prompt}],
                "max_tokens": 8192,
                "temperature": 0.7
            }
        )
        
        # 检查响应
        if response.status_code != 200:
            logger.error(f"API错误: {response.status_code} - {response.text}")
            return {"error": f"API错误: {response.status_code} - {response.text}"}, 500
        
        # 提取结果
        result = response.json()
        ai_response = result["content"][0]["text"]
        
        # 记录日志
        logger.info(f"API响应内容: {ai_response}")
        return {"result": ai_response}, 200
    
    except Exception as e:
        import traceback
        logger.exception(f"发生错误: {str(e)}")
        logger.exception(traceback.format_exc())
        return {"error": f"服务器错误: {str(e)}"}, 500
    

def call_ai_api_test(api_key, model, api_endpoint):
    """
    调用AI API的测试函数，只返回1个token。为测试连接按钮服务
    
    返回:
        AI生成的响应
    """
    user_prompt = "Just say hi and nothing else。"
    
    try:
        # 调用大模型API
        response = requests.post(
            api_endpoint,
            headers = {
                "Content-Type": "application/json",
                "anthropic-version": "2023-06-01",
                "x-api-key": api_key,
            },
            json={
                "model": model,
                #"model": "claude-3-7-sonnet-20250219",  # $15.00/1M
                #"model": "claude-3-5-haiku-20241022", # $4.00/1M
                "system": "",
                "messages": [{"role": "user", "content": user_prompt}],
                "max_tokens": 1,
                "temperature": 0
            }
        )
        
        # 检查响应
        if response.status_code != 200:
            logger.error(f"API错误: {response.status_code} - {response.text}")
            return {"error": f"API错误: {response.status_code} - {response.text}"}, 500
        
        # 提取结果
        result = response.json()
        ai_response = result["content"][0]["text"]
        
        # 记录日志
        logger.info(f"API响应内容: {ai_response}")
        return {"result": ai_response}, 200
    
    except Exception as e:
        import traceback
        logger.exception(f"发生错误: {str(e)}")
        logger.exception(traceback.format_exc())
        return {"error": f"服务器错误: {str(e)}"}, 500

@app.route('/api/test', methods=['POST'])
def test_api():
    try:
        # 获取必要的参数
        api_key = request.json['api_key']
        model = request.json['model']
        api_endpoint = request.json['api_endpoint']

        # 调用API
        result, status_code = call_ai_api_test(api_key, model, api_endpoint)
        return jsonify(result), status_code

    except KeyError as e:
        logger.error(f"缺少必要参数: {str(e)}")
        return {"error": f"缺少必要参数: {str(e)}"}, 400
    except Exception as e:
        import traceback
        logger.exception(f"发生错误: {str(e)}")
        logger.exception(traceback.format_exc())
        return {"error": f"服务器错误: {str(e)}"}, 500


# 武器1：问题之锤
@app.route('/api/generate_hammer', methods=['POST'])
def generate_hammer():
    # 获取用户输入
    user_prompt = request.json['prompt']
    api_key = request.json['api_key']  
    model = request.json['model']
    api_endpoint = request.json['api_endpoint']
    
    # 使用锤子提示词
    system_prompt = prompt.SEVEN_WEAPONS_HAMMER_PROMPT
    
    # 调用API
    result, status_code = call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint)
    
    return jsonify(result), status_code

# 武器2：类比之弓
@app.route('/api/generate_bow', methods=['POST'])
def generate_bow():
    # 获取用户输入
    user_prompt = request.json['prompt']
    api_key = request.json['api_key']  
    model = request.json['model']
    api_endpoint = request.json['api_endpoint']
    
    # 使用弓箭提示词
    system_prompt = prompt.SEVEN_WEAPONS_BOW_PROMPT
    
    # 调用API
    result, status_code = call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint)
    
    return jsonify(result), status_code

# 武器3：定义之矛
@app.route('/api/generate_spear', methods=['POST'])
def generate_spear():
    # 获取用户输入
    user_prompt = request.json['prompt']
    api_key = request.json['api_key']  
    model = request.json['model']
    api_endpoint = request.json['api_endpoint']
    
    # 使用长矛提示词
    system_prompt = prompt.SEVEN_WEAPONS_SPEAR_PROMPT
    
    # 调用API
    result, status_code = call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint)
    
    return jsonify(result), status_code

# 武器4：抽象之梯
@app.route('/api/generate_ladder', methods=['POST'])
def generate_ladder():
    # 获取用户输入
    user_prompt = request.json['prompt']
    api_key = request.json['api_key']  
    model = request.json['model']
    api_endpoint = request.json['api_endpoint']
    
    # 使用梯子提示词
    system_prompt = prompt.SEVEN_WEAPONS_LADDER_PROMPT
    
    # 调用API
    result, status_code = call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint)
    
    return jsonify(result), status_code

# 武器5：质疑之锥
@app.route('/api/generate_awl', methods=['POST'])
def generate_awl():
    # 获取用户输入
    user_prompt = request.json['prompt']
    api_key = request.json['api_key']  
    model = request.json['model']
    api_endpoint = request.json['api_endpoint']
    
    # 使用锥子提示词
    system_prompt = prompt.SEVEN_WEAPONS_AWL_PROMPT
    
    # 调用API
    result, status_code = call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint)
    
    return jsonify(result), status_code

# 武器6：逻辑之刃
@app.route('/api/generate_blade', methods=['POST'])
def generate_blade():
    # 获取用户输入
    user_prompt = request.json['prompt']
    api_key = request.json['api_key']  
    model = request.json['model']
    api_endpoint = request.json['api_endpoint']
    
    # 使用刀刃提示词
    system_prompt = prompt.SEVEN_WEAPONS_BLADE_PROMPT
    
    # 调用API
    result, status_code = call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint)
    
    return jsonify(result), status_code

# 武器7：视角之镜
@app.route('/api/generate_mirror', methods=['POST'])
def generate_mirror():
    # 获取用户输入
    user_prompt = request.json['prompt']
    api_key = request.json['api_key']  
    model = request.json['model']
    api_endpoint = request.json['api_endpoint']
    
    # 使用镜子提示词
    system_prompt = prompt.SEVEN_WEAPONS_MIRROR_PROMPT
    
    # 调用API
    result, status_code = call_ai_api(user_prompt, system_prompt, api_key, model, api_endpoint)
    
    return jsonify(result), status_code

# 如果是直接运行此脚本，则启动服务器
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000, debug=True)